<template>
<div class="row">
  <div class="col-md-12">
    <my-navbar fixed="top">
      <template slot="left"> 
        <validator name="form">
          <div class="form-group">
            <label class="control-label">IP</label>
            <input type="text" class="form-control" v-model="ipaddr" v-validate:ipaddr="{ip: true}">
          </div>
          <div class="form-group">
            <label class="control-label">{{$t("common.module")}}</label>
            <select class="form-control" v-model="port">
              <option v-for="option in moduleOptions" :value="option.value">{{option.text}}</option>
            </select>
          </div>         
          <button class="btn btn-default" @click.prevent="onRefresh">
            <span class="glyphicon glyphicon-refresh"></span> {{$t("common.refresh")}}
          </button> 
        </validator>                          
      </template>       
    </my-navbar>
    <div class="col-md-12">
      <my-table :cfg="cfg" :list="list" :loading="loading"></my-table>
    </div>
  </div>
</div>
</template>

<script>
import {http} from 'share/common/api.js'
import toast from 'libs/toast.js'

export default {
  data () {
    return {
      ipaddr: '',
      port: 9080,
      moduleOptions: [{
        value: 9080,
        text: 'server'
      }, {
        value: 8080,
        text: 'platform'
      }, {
        value: 7080,
        text: 'dev'
      }, {
        value: 6080,
        text: 'media'
      }],
      cfg: {
        checkable: false,
        showHead: false,
        columns: [{
          field: '_id',
          width: '5%',
          name: 'ID'
        }, {
          field: 'link',
          width: 'auto',
          name: 'Link'        
        }]
      },
      list: [],
      loading: false
    }
  },
  computed: {
    host () {
      return `http://${this.ipaddr}:${this.port}`
    }
  },
  methods: {
    makeLink (item) {
      let url = `${this.host}/www/swagger/index.html?url=${this.host}/develop/${item.path}`
      return `<a href="${url}" target="_blank">${item.title}</a>`
    },
    loadData (data) {
      this.list = _.map(data, function(item, index) {
        return {
          _id: index + 1,
          link: this.makeLink(item)
        }
      }.bind(this))
    },
    onRefresh () {
      if (this.$form.invalid) {
        toast.e(this, this.$t('common.fail'), this.$t('error.invalidAddr'))
        return
      }

      http(this.host, '/api/swagger', 'GET').then(function(res) {
        if (res && res.data) {
          this.loadData(res.data)
        } else {
          toast.e(this, this.$t('common.fail'), this.$t('error.unknown'))
        }
      }.bind(this), function(res) {
        toast.e(this, this.$t('common.fail'), this.$t('error.noResponse'))
      }.bind(this))
    }
  }
}
</script>

<style>
body { 
  padding-top: 70px; 
}
</style>